<template>
  <div class="page-container">
    <div class="page-header">
      <h2>ROMA 资源池</h2>
    </div>

    <!-- 搜索栏 -->
    <el-form :inline="true" class="search-form">
      <el-form-item label="资源池名称">
        <el-input
          v-model="searchParams.name"
          placeholder="请输入资源池名称"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="运行状态">
        <el-select
          v-model="searchParams.state"
          placeholder="请选择状态"
          clearable
          @change="handleSearch"
          style="width: 150px"
        >
          <el-option label="RUNNING" value="RUNNING" />
          <el-option label="STOPPED" value="STOPPED" />
          <el-option label="ERROR" value="ERROR" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button @click="handleReset">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
        <el-button @click="loadPools">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table
      :data="displayedPools"
      v-loading="loading"
      stripe
      style="width: 100%"
    >
      <el-table-column prop="id" label="资源池ID" width="280" show-overflow-tooltip />
      <el-table-column prop="name" label="资源池名称" min-width="220" show-overflow-tooltip />
      <el-table-column prop="poolType" label="资源池类型" width="120" />
      <el-table-column prop="state" label="运行状态" width="120">
        <template #default="{ row }">
          <el-tag v-if="row.state" :type="getStateTagType(row.state)">
            {{ row.state }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" min-width="180" show-overflow-tooltip />

      <!-- 节点指标列 -->
      <el-table-column label="配额/总卡数" width="120" align="center">
        <template #default="{ row }">
          {{ row.nodeMetrics?.poolQuotaLimit }}
        </template>
      </el-table-column>
      <el-table-column label="运行(卡)" width="100" align="center">
        <template #default="{ row }">
          {{ row.nodeMetrics?.appRuningNumber }}
        </template>
      </el-table-column>
      <el-table-column label="排队(卡)" width="100" align="center">
        <template #default="{ row }">
          {{ row.nodeMetrics?.appWaitingNumber }}
        </template>
      </el-table-column>
      <el-table-column label="等待(卡)" width="100" align="center">
        <template #default="{ row }">
          {{ row.nodeMetrics?.appQueueNumber }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="100" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="handleViewDetail(row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="pagination.page"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="filteredPools.length"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handlePageChange"
      @current-change="handlePageChange"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { getRomaPoolList } from '@/api/romaPool'

// 状态
const loading = ref(false)
const allPools = ref([])

// 搜索参数
const searchParams = ref({
  name: '',
  state: ''
})

// 分页参数
const pagination = ref({
  page: 1,
  pageSize: 20
})

// 过滤空值字段的函数
const filterEmptyFields = (obj) => {
  if (!obj || typeof obj !== 'object') return obj

  const filtered = {}
  for (const [key, value] of Object.entries(obj)) {
    // 跳过空值: null, undefined, 空字符串, 空数组, 空对象
    // 注意: 0 是有效数值,不应被过滤
    if (value === null || value === undefined || value === '') {
      continue
    }
    if (Array.isArray(value) && value.length === 0) {
      continue
    }
    if (typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length === 0) {
      continue
    }

    // 递归处理嵌套对象
    if (typeof value === 'object' && !Array.isArray(value)) {
      const nestedFiltered = filterEmptyFields(value)
      if (Object.keys(nestedFiltered).length > 0) {
        filtered[key] = nestedFiltered
      }
    } else {
      filtered[key] = value
    }
  }
  return filtered
}

// 过滤后的资源池列表（根据搜索条件）
const filteredPools = computed(() => {
  let pools = allPools.value

  // 按名称过滤
  if (searchParams.value.name) {
    pools = pools.filter(pool =>
      pool.name?.toLowerCase().includes(searchParams.value.name.toLowerCase())
    )
  }

  // 按状态过滤
  if (searchParams.value.state) {
    pools = pools.filter(pool => pool.state === searchParams.value.state)
  }

  return pools
})

// 分页后的显示列表
const displayedPools = computed(() => {
  const start = (pagination.value.page - 1) * pagination.value.pageSize
  const end = start + pagination.value.pageSize
  return filteredPools.value.slice(start, end)
})

// 获取状态标签类型
const getStateTagType = (state) => {
  const stateMap = {
    'RUNNING': 'success',
    'STOPPED': 'info',
    'ERROR': 'danger',
    'PENDING': 'warning'
  }
  return stateMap[state] || 'info'
}

// 加载资源池列表
const loadPools = async () => {
  loading.value = true
  try {
    const response = await getRomaPoolList()
    // 过滤每个资源池的空值字段
    allPools.value = (response.pools || []).map(pool => filterEmptyFields(pool))
    ElMessage.success('资源池列表加载成功')
  } catch (error) {
    console.error('加载资源池列表失败:', error)
    ElMessage.error(error.message || '加载资源池列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.page = 1
}

// 重置搜索
const handleReset = () => {
  searchParams.value = {
    name: '',
    state: ''
  }
  pagination.value.page = 1
}

// 分页改变
const handlePageChange = () => {
  // 分页参数已通过 v-model 自动更新
}

// 查看详情（跳转到固定页面）
const handleViewDetail = (row) => {
  const url = 'https://csb.roma.huawei.com/csb/#/hec/eiwizard/dectrescpol/com.app.bmc.ai.aicase/develop'
  window.open(url, '_blank')
}

// 组件挂载时加载数据
onMounted(() => {
  loadPools()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 500;
}

.search-form {
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>
